'''
Created on 03.06.2012

@author: johannes
'''

# Borrowed heavily from: http://amundblog.blogspot.com/2008/12/ajax-with-python-combining-pyjs-and.html

import cgi
import logging
from google.appengine.ext import webapp

try:
    import json
except:
    from django.utils import simplejson as json

class JsonHandler(webapp.RequestHandler):
    def post(self):
        args = json.loads(cgi.escape(self.request.body))
        logging.info('post: args: '+str(args))
        json_func = getattr(self, args[u"method"])
        logging.info('post: method: '+str(json_func))
        json_params = args[u"params"]
        json_method_id = args[u"id"]
        result = json_func(*json_params)
        logging.info('post: result: '+str(result))
        # reuse args to send result back
        args.pop(u"method")
        args["result"] = result
        args["error"] = None # IMPORTANT!!
        self.response.headers['Content-Type'] = 'application/json'
        self.response.set_status(200)
        self.response.out.write(json.dumps(args))
        #return json.dumps(args)
#    def get(self):
#        args = json.loads(cgi.escape(self.request.body))
#        logging.info('get: args: '+str(args))
#        json_func = getattr(self, args[u"method"])
#        logging.info('get: method: '+str(json_func))
#        json_params = args[u"params"]
#        json_method_id = args[u"id"]
#        result = json_func(*json_params)
#        logging.info('get: result: '+str(result))
#        # reuse args to send result back
#        args.pop(u"method")
#        args["result"] = result
#        args["error"] = None # IMPORTANT!!
#        self.response.headers['Content-Type'] = 'application/json'
#        self.response.set_status(200)
#        self.response.out.write(json.dumps(args))